<template>
  <div class="container">
    <div class="main-content">
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="10" animated />
      </div>

      <template v-else>
        <div class="blog-header">
          <h1 class="blog-title">{{ blog.title }}</h1>
          <div class="blog-meta">
            <span class="author">{{ blog.author }}</span>
            <span class="time">{{ blog.createTime }}</span>
            <span class="views">阅读 {{ blog.views }}</span>
          </div>
        </div>

        <div class="blog-content">{{ blog.content }}</div>

        <div class="blog-actions">
          <el-button type="primary" size="small" :disabled="blog.hasAgreed" @click="handleAgree">
            <el-icon>
              <StarFilled />
            </el-icon>
            点赞 ({{ blog.agrees }})
          </el-button>
          <el-button type="primary" size="small">
            <el-icon>
              <ChatRound />
            </el-icon>
            评论 ({{ blog.comments?.length || 0 }})
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleCollect"
          >
            <el-icon>
              <Collection />
            </el-icon>
            {{ blog.hasCollected? '已收藏' : '收藏' }} ({{blog.collection}})
          </el-button>
        </div>

        <div class="comment-section">
          <div class="comment-editor">
            <el-input
              v-model="commentContent"
              v-profanity-filter
              type="textarea"
              rows="3"
              placeholder="写下你的评论..."
            />
            <el-button type="primary" style="margin-top: 12px" @click="handleComment">发表评论</el-button>
          </div>

          <div class="comment-list">
            <div v-for="comment in blog.comments" :key="comment.id" class="comment-item">
              <div class="comment-user">
                <el-avatar size="small" :src="comment.avatar" />
                <span class="username">{{ comment.username }}</span>
                <span class="time">{{ comment.createTime }}</span>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <div class="comment-actions">
                <el-button type="text" size="small" @click="handleReply(comment)">回复</el-button>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>

    <div class="side-content">
      <div class="author-card">
        <div class="author-info">
          <el-avatar :size="50" :src="blog.authorAvatar" />
          <div class="author-meta">
            <div class="author-name">{{ blog.author }}</div>
            <div class="author-stats">
              <span>文章 {{ blog.authorStats?.posts || 0 }}</span>
              <span>粉丝 {{ blog.authorStats?.followers || 0 }}</span>
            </div>
          </div>
        </div>
        <el-button
          type="primary"
          class="follow-btn"
          @click="handleFollow"
        >{{ blog.hasFollowed ? '已关注' : '关注' }}</el-button>
      </div>

      <div class="related-blogs">
        <h3>相关文章</h3>
        <ul>
          <li v-for="item in relatedBlogs" :key="item.id">
            <a href="#" @click.prevent="handleRelatedClick(item.id)">{{ item.title }}</a>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { StarFilled, ChatRound, Collection } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  getBlogDetail,
  getRelatedBlogs,
  agreeBlog,
  createComment
} from "@/api/blog";
import { followAuthor, cancelFollow } from "@/api/user";
import { collectBlog, cancelCollectBlog } from "@/api/blog";

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const blog = ref({});
const relatedBlogs = ref([]);
const commentContent = ref("");

// 获取博客详情
const fetchBlogDetail = async () => {
  try {
    loading.value = true;
    const { id } = route.params;
    const { data } = await getBlogDetail(id);
    blog.value = data;
  } catch (error) {
    ElMessage.error("获取博客详情失败");
  } finally {
    loading.value = false;
  }
};

// 获取相关博客
const fetchRelatedBlogs = async () => {
  try {
    const { data } = await getRelatedBlogs(route.params.id);
    relatedBlogs.value = data;
  } catch (error) {
    console.error("获取相关博客失败:", error);
  }
};

// 点赞
const handleAgree = async () => {
  try {
    await agreeBlog(blog.value.id);
    // blog.value.agrees++
    blog.value.hasAgreed = true;
    ElMessage.success("点赞成功");
    const { data } = await getBlogDetail(blog.value.id);
    blog.value = data;
  } catch (error) {
    ElMessage.error("点赞失败");
  }
};

// 关注作者
const handleFollow = async () => {
  if (blog.value.hasFollowed) {
    try {
      await cancelFollow(blog.value.authorId);
      blog.value.hasFollowed = false;
      ElMessage.success("取消成功");
      const { data } = await getBlogDetail(blog.value.id);
      blog.value = data;
    } catch (error) {
      ElMessage.error("取消关注失败");
    }
  } else
    try {
      await followAuthor(blog.value.authorId);
      blog.value.hasFollowed = true;
      ElMessage.success("关注成功");
      const { data } = await getBlogDetail(blog.value.id);
      blog.value = data;
    } catch (error) {
      ElMessage.error("关注失败");
    }
};

// 收藏
const handleCollect = async () => {
  if (blog.value.hasCollected) {
    try {
      await cancelCollectBlog(blog.value.id);
      blog.value.hasCollected = false;
      ElMessage.success("取消成功");
      const { data } = await getBlogDetail(blog.value.id);
      blog.value = data;
    } catch (error) {
      ElMessage.error("取消收藏失败");
    }
  } else
    try {
      await collectBlog(blog.value.id);
      // blog.value.hasCollected = true;
      ElMessage.success("收藏成功");
      const { data } = await getBlogDetail(blog.value.id);
      blog.value = data;
    } catch (error) {
      ElMessage.error("收藏失败");
    }
};

// 发表评论
const handleComment = async () => {
  if (!commentContent.value.trim()) {
    return ElMessage.warning("请输入评论内容");
  }

  try {
    const { data: newComment } = await createComment(
      blog.value.id,
      commentContent.value
    );
    blog.value.comments = [...(blog.value.comments || []), newComment];
    commentContent.value = "";
    ElMessage.success("评论成功");
    const { data } = await getBlogDetail(blog.value.id);
    blog.value = data;
  } catch (error) {
    ElMessage.error("评论失败");
  }
};

// 点击相关文章
const handleRelatedClick = id => {
  router.push(`/blog/${id}`);
};

// 回复评论
const handleReply = comment => {
  commentContent.value = `@${comment.username} `;
};

onMounted(() => {
  fetchBlogDetail();
  fetchRelatedBlogs();
});
</script>

<style scoped>
.container {
  display: flex;
  gap: 20px;
  padding: 20px 0;
}

.main-content {
  flex: 1;
  min-width: 0;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.side-content {
  width: 300px;
  flex-shrink: 0;
}

.blog-header {
  margin-bottom: 24px;
}

.blog-title {
  font-size: 24px;
  margin: 0 0 16px;
}

.blog-meta {
  display: flex;
  gap: 16px;
  color: #666;
  font-size: 14px;
}

.blog-content {
  line-height: 1.8;
  margin-bottom: 24px;
}

.blog-actions {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.comment-section {
  border-top: 1px solid #eee;
  padding-top: 24px;
}

.comment-item {
  padding: 16px 0;
  border-bottom: 1px solid #eee;
}

.comment-user {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.username {
  font-weight: 500;
}

.time {
  color: #999;
  font-size: 12px;
}

.comment-content {
  margin: 8px 0;
  line-height: 1.6;
}

.author-card {
  background: #fff;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

.author-info {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.author-meta {
  flex: 1;
}

.author-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.author-stats {
  color: #666;
  font-size: 14px;
  display: flex;
  gap: 16px;
}

.follow-btn {
  width: 100%;
}

.related-blogs {
  background: #fff;
  border-radius: 4px;
  padding: 16px;
}

.related-blogs h3 {
  margin: 0 0 16px;
  font-size: 16px;
}

.related-blogs ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.related-blogs li {
  margin-bottom: 12px;
}

.related-blogs a {
  color: #333;
  text-decoration: none;
}

.related-blogs a:hover {
  color: var(--el-color-primary);
}

.loading-state {
  padding: 20px;
}

.comment-editor {
  margin-bottom: 24px;
}
</style>